var sh_address = false;
$(function(){
	
	if(user == null || user == ''){
   		$("#loginOrRegist").show();
   	}else {
   		$("#top-index-usersName").text(user.usersName);
   		$("#usersName").show();
   	}
	
	//得到产品ID
	var proId = getParameter('proId');
	//查询产品信息
	var url = "../product/findById.action";
	var data = {"proId":proId};
	$.ajax({
		url:url,
		data:data,
		success:function(msg){
			$($(".p-img").find("img")).attr("alt",msg.proName);
			$($(".p-img").find("img")).attr("src","../"+msg.imgPath);
			$(".p-name").attr("title",msg.proName);
			$(".p-name").text(msg.proName);
			$("#proNumber").text("×"+" "+getParameter('proQuantity'));
			$(".p-price").html("¥&nbsp;"+(parseInt(getParameter('proQuantity')) * parseInt(msg.proPrice)));
		}
	});
	//查询收货地址
	findAddress();
});
//查询收货地址
function findAddress(){
	if(user != null && user != ""){
		var url = "../address/findByUserIdAllAddress.action";
		var data = null;
		$.ajax({
			url:url,
			data:data,
			async:false,
			success:function(msg){
				if(msg != null || msg != ""){
					$("#list-address").html("");
					for(var i=0;i<msg.length;i++){
						$("#list-address").append('<li id="'+msg[i].addressId+'" ap="'+msg[i].addressPeople+'" aphone="'+msg[i].addressPhone+'" province="'+msg[i].province+'" city="'+msg[i].city+'" county="'+msg[i].county+'" da="'+msg[i].detailAddress+'"'
											+'onclick="current(\''+msg[i].addressId+'\')"><div class="address-main">'
											+'<p class="clearfix"><b id="consignee-name-62353514">'+msg[i].addressPeople+'</b><span id="consignee-tel-62353514">'+msg[i].addressPhone+'</span>'
											+'</p><div class="address-detail">'+msg[i].province+'&nbsp;'+msg[i].city+'&nbsp;'+msg[i].county+'&nbsp;'+msg[i].detailAddress+'</div></div>'
											+'<div class="address-sub"><a class="address-edit" href="javascript:edit_address(\''+msg[i].addressId+'\');">编辑</a><a class="address-del" href="javascript:del_address(\''+msg[i].addressId+'\');"'
											+'>删除</a></div></li>');
					}
					$("#list-address").append('<li id="address-empty"><div class="address-empty">'
							+'<a href="javascript:;" class="address-add-btn"'
							+'onclick="add_address()">新增收货地址</a></div></li>');
				}
				
			}
		});
	}
}
//选中地址
function current(addressId){
	sh_address = true;
	$("#addressId").val(addressId);
	$($("li.current")).attr("class","");
	$("#"+addressId).attr("class","current");
	var addressPeople = $("#"+addressId).attr("ap");
	var addressPhone = $("#"+addressId).attr("aphone");
	var province = $("#"+addressId).attr("province");
	var city = $("#"+addressId).attr("city");
	var county = $("#"+addressId).attr("county");
	var detailAddress = $("#"+addressId).attr("da");
	$("#addressID").html(province+'&nbsp;'+city+'&nbsp;'+county+'&nbsp;'+detailAddress);
	$("#peopleID").text(addressPeople);
	$("#telID").text(addressPhone);
}

//弹出增加收货地址框
function add_address(){
	$(".ol_box_mask").attr("style","visibility: visible; width: 100%; height: 100%; z-index: 5000;");
	$("#myAddress-add-new-box").attr("style","visibility: visible; position: fixed; top: 113px; left: 274px; z-index: 5000; width: 800px;");
}
//取消增加收货地址
function cancel(){
	$(".ol_box_mask").attr("style","visibility: hidden; width: 100%; height: 100%; z-index: 5000;");
	$("#myAddress-add-new-box").attr("style","visibility: hidden; position: fixed; top: 113px; left: 274px; z-index: 5000; width: 800px;");
}

layui.use(['laydate', 'laypage', 'layer', 'table', 'upload', 'element'], function(){
	  var laydate = layui.laydate //日期
	  ,laypage = layui.laypage //分页
	  layer = layui.layer //弹层
	  ,table = layui.table //表格
	  ,upload = layui.upload //上传
	  ,element = layui.element; //元素操作
	  
	  $("#top-index-loginUrl").click(function(){
		  layer.open({
			  title: ' '
			  ,type: 2
			  ,area: ['38%','74%']
			  ,content: 'login.html'
			});
	  });
	  $("#top-index-registUrl").click(function(){
		  layer.open({
			  title: ' '
			  ,type: 2
			  ,area: ['38%','74%']
			  ,content: 'regist.html'
			});
	  });
	  
	//提交订单
		$("#checkoutSubmit").click(function(){
			if(sh_address == false){
				layer.open({
					title:"提示",
					content:"请选择收货地址"
				});
			}else {
				var addressId = $("#addressId").val();
				var number = getParameter('proQuantity');
				var str = $("#totalPrice").text();
				var totalPrice = str.substring(2,str.length);
				var url = "../order/save.action";
				var data = {"addressId":addressId,"ordersNumber":number,"ordersSummoney":totalPrice,"proId":getParameter('proId')};
				$.ajax({
					url:url,
					data:data,
					success:function(msg){
						if(msg.state == "1"){
							layer.open({
								  content: '您的订单提交成功!是否立即支付'
								  ,btn: ['确定', '取消']
								  ,yes: function(index, layero){
								   var url = "../order/update.action";
								    var data = {"ordersState":"2"};
								    $.ajax({
								    	url:url,
								    	data:data,
								    	success:function(msg){
								    		if(msg.state == "1"){
								    			layer.msg("支付成功!",{icon:1,time:1000},function(){
								    				location.href = "index.html";
								    			});
								    		}else {
								    			layer.msg("支付失败!",{icon:1,time:1000},function(){
								    				location.href = "index.html";
								    			});
								    		}
								    	}
								    });
								  }
								  ,btn2: function(index, layero){
								    location.href = "index.html";
								  }
								});
						}else {
							layer.msg("提交失败!",{icon:2,time:1000},function(){
								/*location.href = "index.html";*/
							});
						}
					}
				});
			}
		});
		
		//保存收货地址
		  $("#button-ok").click(function(){
			  var addressId = $("#addressIds").val();
			  var addressPeople = $("#addressPeople").val();
			  var addressPhone = $("#addressPhone").val();
			  var dizhi = $("#city").val();
			  var detailAddress = $("#detailAddress").val();
			  var arr = dizhi.split("/");
			  var province = "";
			  var city = "";
			  var county = "";
			  
			  if((addressPeople != null && addressPeople != "") && (addressPhone != null && addressPhone != "")
					  && (dizhi != null && dizhi != "") && (detailAddress != null && detailAddress != "")){
				  
				  if(arr.length == 2){
						 province = arr[0];
						  city = arr[1];
					  }else if(arr.length == 3){
						  province = arr[0];
						  city = arr[1];
						  county = arr[2];
					  }
					  var data = {"userId":user.usersId,"addressId":addressId,"addressPeople":addressPeople,"addressPhone":addressPhone,"province":province,"city":city,"county":county,"detailAddress":detailAddress};
					  var url = "../address/saveOrUpdate.action";
					  $.ajax({
						  url:url,
						  data:data,
						  success:function(msg){
							  if(msg.state == "1"){
								  layer.msg(msg.msg,{icon:1,time:1000});
								  findAddress();
								  $(".ol_box_mask").attr("style","visibility: hidden; width: 100%; height: 100%; z-index: 5000;");
								  $("#myAddress-add-new-box").attr("style","visibility: hidden; position: fixed; top: 113px; left: 274px; z-index: 5000; width: 800px;");
							  }else {
								  layer.msg(msg.msg,{icon:2,time:1000});
								  $(".ol_box_mask").attr("style","visibility: hidden; width: 100%; height: 100%; z-index: 5000;");
								  $("#myAddress-add-new-box").attr("style","visibility: hidden; position: fixed; top: 113px; left: 274px; z-index: 5000; width: 800px;");
							  }
						  }
					  });
				  
			  }else {
				  layer.msg("请把相关信息填写完善!",{icon:5,time:1000,anim:6});
			  }
			  
			  
		  });
		  
		//限制手机号码数字输入
		  $("#addressPhone").keyup(function(event){
				var obj = event.target;
				var phone = $(obj).val();
				//限制只能输入数字的正则表达式
				var reg = new RegExp("^[0-9]*$");
				if(!reg.test(phone)){
					$(obj).val("");
					return false;
					//限制长度
				}else if(phone.length > 11){
					$(obj).val(phone.substring(0,11));
				}
			})
		//手机号码正则表达式
		  $("#addressPhone").blur(function(){
			var obj = event.target;
			var phone = $(obj).val();
			//验证输入有效的手机号码
			if(!(/^1[34578]\d{9}$/.test(phone))){
		    	layer.msg('请输入有效的手机号码!', {icon:5,time:1000,anim:6});
		    	$(obj).val("");
		        return false; 
		    }
		  });
});
//删除收货地址
function del_address(addressId){
	var url = "../address/deletes.action";
	var data = {"addressId":addressId};
	$.ajax({
		url:url,
		data:data,
		success:function(msg){
			if(msg.state == "1"){
				$("#"+addressId).remove();
			}
		}
	});
}
//修改收货地址
function edit_address(addressId){
	$(".ol_box_mask").attr("style","visibility: visible; width: 100%; height: 100%; z-index: 5000;");
	$("#myAddress-add-new-box").attr("style","visibility: visible; position: fixed; top: 113px; left: 274px; z-index: 5000; width: 800px;");
	var url = "../address/findById.action";
	var data = {"addressId":addressId};
	$.ajax({
		url:url,
		data:data,
		success:function(msg){
			$("#addressIds").val(msg.addressId);
			$("#addressPeople").val(msg.addressPeople);
			$("#addressPhone").val(msg.addressPhone);
			if(msg.county != null && msg.county != ""){
				$("#city").val(msg.province+"/"+msg.city+"/"+msg.county);
			}else {
				$("#city").val(msg.province+"/"+msg.city);
			}
			$("#detailAddress").val(msg.detailAddress);
		}
	});
}